'use client';

import React, { useCallback, useMemo, useRef } from 'react';
import clsx from 'clsx';
import toast from 'react-hot-toast';
import { CloudUploadOutlined } from '@ant-design/icons';
import { XMarkIcon } from '@heroicons/react/24/outline';
import { FormImage } from './FormImage';
import { insertImage } from 'src/actions/image';
import { useSearchParams } from 'next/navigation';
import type { UseFormReturn } from 'react-hook-form';
import type { FormImageProps, Values } from './FormImage';

export interface FuncNewImageProps {
  className?: string;
  modalClassName?: string;
  onSuccess?: () => void;
}

function FuncNewImageNoMemoized(props: FuncNewImageProps) {
  const { className, modalClassName, onSuccess } = props;

  // Refs
  const dialog = useRef<HTMLDialogElement>(null);
  const formImage = useRef<UseFormReturn<Values>>(null);

  // Hooks

  const searchParams = useSearchParams();
  const folderId = searchParams.get('folderId') ?? undefined;

  // Memoized
  const defaultValues = useMemo<FormImageProps['defaultValues']>(() => {
    // 默认选中第一个存储系统
    return {
      isPublic: true,
    };
  }, []);

  // Handler
  const handleDialogClose = useCallback(() => {
    if (dialog.current) {
      dialog.current.close();
      formImage.current?.reset();
    }
  }, []);

  const handleDialogOpen = useCallback(() => {
    if (dialog.current) {
      dialog.current.show(); // 不要用 showModal，否则会导致 dialog 被标为 top-layer 永远置为最上层, 任何元素都无法覆盖该元素
    }
  }, []);

  const handleSubmit = useCallback<NonNullable<FormImageProps['onSubmit']>>(
    async (data) => {
      await insertImage({ ...data, folderId });
      toast.success('图片上传成功');
      handleDialogClose();
      onSuccess?.();
    },
    [folderId, handleDialogClose, onSuccess]
  );

  return (
    <>
      <button
        type="button"
        className={clsx('btn btn-sm btn-ghost rounded-full text-base', className)}
        title="上传图片"
        onClick={handleDialogOpen}
      >
        <CloudUploadOutlined />
      </button>

      <dialog ref={dialog} className={clsx('modal', modalClassName)}>
        <div className="modal-box">
          <button
            className="btn btn-sm btn-circle btn-ghost absolute right-2 top-2"
            onClick={handleDialogClose}
          >
            <XMarkIcon className="size-4" />
          </button>
          <h3 className="font-bold text-lg">上传图片</h3>
          <div className="py-4">
            <FormImage ref={formImage} defaultValues={defaultValues} onSubmit={handleSubmit} />
          </div>
        </div>
      </dialog>
    </>
  );
}

export const FuncNewImage = React.memo(FuncNewImageNoMemoized);
